import { Form, message } from 'antd';
import { NeedUpdateService } from '../services/UpdateService';
import { IActionEnum } from './NeedReducer';
import { ILoadMapTypeAll } from '@/common';
import { history } from 'umi';

import { useState, useEffect, useMemo } from 'react';
import { fieldFlowExport, getKeyRouter, getPosIDs, getTenantID, getUserDepName, getUserID } from '@/utils';
import { JZLZ_STATE, SHZ_STATE, XQBZ_STATE, getFormattedDateString, isExpectPriceNull, purchaseNeedCategory } from './Format';
import { SHTH_CHECKSTATE, SHZ_CHECKSTATE, formatDecimal } from '../../Acommon';

const { success, warning } = message;

interface processResponeState {
  flag: boolean;
  message: string;
  id: string;
}

/**
 * @useNeedUpdate 详情页hooks逻辑
 * @param needInfo 当前需求信息
 * @param materials 当前需求对应的物料信息
 * @param dispatch 派发器
 * @returns
 */
export function useNeedUpdate({
  locationProps,
  materialList,
  dispatch,
}: {
  locationProps: Record<string, any>;
  materialList: Record<string, any>[];
  dispatch: any;
}) {
  // 表单实例
  const [tableForm] = Form.useForm();

  // 路由跳转来携带的数据
  const { info = {}, supplyWay, isView } = locationProps?.state || {};

  // 存储当前的需求信息，用来数据显示以及对接接口参数
  const [needInfo, setNeedInfo] = useState<Record<string, any>>({});

  // 最新需求物料列表信息
  const [needAndMaterialParam, setNeedAndMaterialParam] = useState<Record<string, any>>({});

  // 取消需求渲染状态
  const [isShowCancel, setIsShowCancel] = useState<boolean>(false);

  // 审批记录抽屉渲染状态
  const [isShowAuditRecord, setIsShowAuditRecord] = useState<boolean>(false);

  // TODO: 梁豪杰 暂时默认 （需求名称默认生成 格式XX部门/团队 2023年 XX月采购需求）
  const [needTitle] = useState<string>(getUserDepName() + '_' + getFormattedDateString());

  // 物料信息渲染状态
  const [isShowMaterial, setIsShowMaterial] = useState<boolean>(false);

  // 物料详情渲染状态
  const [isShowMaterialDetail, setIsShowMaterialDetail] = useState<{ id: string; isShow: boolean }>({
    id: '',
    isShow: false,
  });

  // 保存详情返回的物料id
  const [materialRowList, setMaterialIDList] = useState<any[]>([]);

  // 点击按钮保存数据和弹框控制  =============================工作流使用STATE==============================
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  const onChangeWorkFlowInfoObj = (params: Record<string, any>) => setWorkFlowInfoObj(params);
  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };
  const [isShowWorkflowCheck, setIsShowWorkflowCheck] = useState<Record<string, any>>({
    isShow: false,
    resObj: null,
  });
  const onChangeWorkflowCheck = (params: Record<string, any>) => setIsShowWorkflowCheck(params);
  // 是否展示审核弹窗  =============================工作流使用END==============================

  // 作废表单实例
  const [cancelForm] = Form.useForm();
  // 审核表单实例
  const [examineForm] = Form.useForm();

  // 保存最新需求物料列表，同步物料弹窗回显选中物料，在需求详情，修改物料表格数据后自动调用
  const saveNeedAndMaterialParam = (params: Record<string, any>) => {
    // debugger
    setNeedAndMaterialParam(params);
  };

  // 是否可以办理流程
  const nodesFlowListMemo = useMemo(() => {
    /** 演示注释:【振豪本地无工作流数据，所以要直接返回true】 */
    const taskHandInfo: Record<string, any> = needInfo?.paramObject?.[purchaseNeedCategory()];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      return taskHandInfo?.mactivitiTaskList?.[0];
    } else {
      return false;
    }

    // return true // [演示]
  }, [needInfo?.paramObject]);

  // API 接口
  const {
    addNeedService,
    findNeedService,
    editNeedService,
    auditNeedService,
    cancelNeedService,
    modifyNeedStateService,
    exportNeedService,
  } = NeedUpdateService();

  const { addNeedRun, addNeedLoading } = addNeedService();
  const { findNeedRun, findNeedLoading } = findNeedService();
  const { editNeedRun, editNeedLoading } = editNeedService();
  const { auditNeedRun, auditNeedLoading } = auditNeedService();
  const { cancelNeedRun, cancelNeedLoading } = cancelNeedService();
  const { modifyNeedStateRun, modifyNeedStateLoading } = modifyNeedStateService();
  const { exportNeedRun, exportNeedLoading } = exportNeedService();

  // 全局loading
  const loading = useMemo(() => {
    return addNeedLoading || findNeedLoading || editNeedLoading || auditNeedLoading || cancelNeedLoading || modifyNeedStateLoading || exportNeedLoading;
  }, [addNeedLoading, findNeedLoading, editNeedLoading, auditNeedLoading, cancelNeedLoading, modifyNeedStateLoading, exportNeedLoading]);

  /**查询需求详情 */
  const fetchFindNeed = async (params: Record<string, any>, workflag = false) => {
    const result = await findNeedRun(params);
    if (result?.msgFlag) {
      message?.success(result?.msg);
      // 以下是保存详情信息使用
      const materialData = result?.obj?.purchaseNeedMaterials?.map((item: Record<string, any>) => {
        let needProofFlag = 0;
        if (Number(item?.expectSum) >= 500000) {
          needProofFlag = 1;
        }
        return {
          ...item,
          materialIDS: item?.materialID + getKeyRouter() + new Date()?.getTime(),
          needProofFlag,
          isOriginData: true /** 给原始数据添加标识，用来区分接口获取的数据与手动新增的数据，目的用的控制数据是否可编辑 */,
        };
      });
      // 存储结构
      const data = {
        ...result?.obj,
        material: materialData,
      };
      // 存储当前需求详情
      setNeedInfo(data);
      // 保存第一次的数据
      setMaterialIDList(materialData);
      // 保存到上下文
      dispatch({
        type: IActionEnum.UPDATE_MATERIAL_LIST,
        payload: data.material ?? [],
      });

      if (workflag) {
        setWorkFlowInfoObj({
          selectFlowRows: data,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      }
    }
  };

  /**
   * @processResponse 处理请求响应
   * @description 处理操作后重新请求最新数据
   * @param flag msgFlag 状态
   * @param message msg 信息
   * @param id 当前需求ID
   * @returns
   */
  const processResponse = ({ flag, message, id }: processResponeState, workflag = false) => {
    if (flag) {
      success(message);
      id && fetchFindNeed({ id }, workflag);
    } else {
      warning(message);
    }
    return flag;
  };

  /**修改状态 */
  const fetchModifyNeedState = async (params: Record<string, any>) => {
    const { msgFlag, msg } = await modifyNeedStateRun(params);
    return processResponse({ flag: msgFlag, message: msg, id: needInfo.id });
  };

  /**新增需求 */
  const fetchAddNeed = async (params: Record<string, any>, flag = false) => {
    const { msgFlag, msg, obj } = await addNeedRun(params);
    return processResponse({ flag: msgFlag, message: msg, id: obj }, flag);
  };

  /**编辑需求 */
  const fetchEditNeed = async (params: Record<string, any>, flag = false) => {
    const { msgFlag, msg } = await editNeedRun(params);
    return processResponse({ flag: msgFlag, message: msg, id: needInfo.id }, flag);
  };

  /**审核需求 */
  const fetchAuditNeed = async (params: Record<string, any>) => {
    const { msgFlag, msg } = await auditNeedRun(params);
    return processResponse({ flag: msgFlag, message: msg, id: needInfo.id });
  };

  /**作废需求 */
  const fetchCancelNeed = async (params: Record<string, any>) => {
    const { msgFlag, msg } = await cancelNeedRun(params);
    return processResponse({ flag: msgFlag, message: msg, id: needInfo.id });
  };

  /**需求物料导出 */
  const fetchExportNeed = async () => {
    const obj = await exportNeedRun({ id: needInfo.id });
    fieldFlowExport(obj, `需求物料信息.xlsx`);
  };

  /**自动获取详情方法 ==================工作流使用======================*/
  const reloadInfoFunc = () => {
    fetchFindNeed({ id: needInfo.id });
  };

  // 修改渲染状态，包装一层提高扩展能力
  const onChangeMaterialModalState = (state: boolean) => setIsShowMaterial(state);
  const onChangeCancelModalState = (state: boolean) => {
    cancelForm?.resetFields();
    setIsShowCancel(state);
  };
  const onChangeAuditRecordDrawerState = (state: boolean) => setIsShowAuditRecord(state);
  const onChangeMaterialDetailDrawerState = (params: { id: string; isShow: boolean }) => setIsShowMaterialDetail(params);

  /**
   * @submit 数据提交事件
   * @baseInfoSubmit 暂存物料
   * @examineSubmit 审核事件
   * @cancelSubmit 作废事件
   */

  const submit = {
    baseInfoSubmit: async (operate: string, submitFlag = false) => {
      /**没有选择物料*/
      if (!materialList.length) {
        warning('请选择需要采购的物料！');
        return;
      }

      /**supplyWay['月度计划']*/
      const purchaseNeedMaterials = needAndMaterialParam?.list?.map((item: Record<string, any>) => {
        // 当预算金额小于100w时，checkState为通过【体现在主任办公会审议】
        // let checkState = 0;
        // 【主任办公会审议】在2024/11/22需求沟通会议中被删除 因此判断失效
        // if (Number(item?.expectSum) < 1000000) {
        //   checkState = 1;
        // }

        return {
          ...item,
          supplyWay: supplyWay ?? needInfo?.supplyWay,
          materialID: item?.materialIDS,
          checkState: 1,
        };
      });

      /**接口参数整理*/
      const params: Record<string, any> = {
        ...needInfo,
        needName: needTitle,
        supplyWay: supplyWay ?? needInfo?.supplyWay,
        needType: 1,
        expectSum: needAndMaterialParam?.totalNeedPrice,
        purchaseNeedMaterials: purchaseNeedMaterials,
      };

      /**校验【项目是否填写】  */
      const isSelectType = purchaseNeedMaterials?.find((item) => !item?.projectCode);
      if (isSelectType) {
        message?.error('请选择项目来源！');
        return;
      }

      /**校验【标的类别】 2024/11/22需求沟通 删除标的类别 */
      // const isSelectType = purchaseNeedMaterials?.find((item) => item?.supplyType == `${getTenantID()}${ILoadMapTypeAll.PURCHASE_CATEGORY}1000`);
      // if (isSelectType) {
      //   message?.error('请选择标的类别！');
      //   return;
      // }

      /**校验【'技术规范'+'调研报告'是必传项】*/
      // const isUploadFile = purchaseNeedMaterials?.find((item) => !item?.skillNormURL || !item?.researchReportURL);
      // if (isUploadFile) {
      //   message?.error('请上传技术报告和调研报告！');
      //   return;
      // }

      /**删除material字段【后端要求】*/
      delete params?.material;

      /**判断预付金额*/
      const isExpectPrice = isExpectPriceNull(needAndMaterialParam);

      if (operate === '暂存') {
        // 如果是在详情页面点击提交，那么就不需要再调用编辑接口了
        if (isView && submitFlag) {
          setWorkFlowInfoObj({
            selectFlowRows: needInfo,
            showWorkFlowModal: true,
            saveNoDefaultFlowID: '',
          });
          return;
        }

        /**needType 暂存事件 首次为0，后续编辑时默认使用当前needType*/
        params.needType = needInfo?.needType ?? 0;

        /**这里处理是因为后端需要返回已经删除了的物料id 【materialIDList === 需求物料id】*/
        let delNeedMaterialIds: any[] = [];
        const newMaterialIDS = purchaseNeedMaterials?.map((i: Record<string, any>) => i?.id);
        materialRowList?.forEach((item: Record<string, any>) => {
          if (!newMaterialIDS?.includes(item?.id)) {
            delNeedMaterialIds?.push(item?.id);
          }
        });

        /**新增物料的处理*/
        let purchaseNeedMaterial: any[] = [];
        purchaseNeedMaterials?.forEach((item: Record<string, any>) => {
          if (item?.id === item?.materialID) {
            purchaseNeedMaterial?.push({
              ...item,
              id: null,
              expectNum: formatDecimal(item?.expectNum),
              expectPrice: formatDecimal(item?.expectPrice),
            });
          } else {
            purchaseNeedMaterial?.push({
              ...item,
              expectNum: formatDecimal(item?.expectNum),
              expectPrice: formatDecimal(item?.expectPrice),
            });
          }
        });

        /**如有原本就在需求中的，被删除后又添加回来，匹配物料id，赋值需求物料id*/
        const oldMaterialIds = materialRowList?.map((i: Record<string, any>) => i?.materialID);
        oldMaterialIds?.forEach((item: Record<string, any>, index) => {
          purchaseNeedMaterial?.forEach((items: Record<string, any>, indexs: number) => {
            if (item === items?.materialID) {
              items.id = materialRowList[index]?.id;
              delNeedMaterialIds = delNeedMaterialIds?.filter((item) => item != materialRowList[index]?.id);
            }
          });
        });
        const paramsObj: Record<string, any> = {
          ...params,
          delNeedMaterialIds: delNeedMaterialIds?.join(','),
          purchaseNeedMaterials: purchaseNeedMaterial,
        };

        // return

        /**校验【预估单价不能为空】*/
        if (!isExpectPrice) {
          message.error('请输入预估单价（元）！');
          return;
        }

        if (paramsObj?.id) {
          fetchEditNeed(paramsObj, submitFlag); //编辑
        } else {
          fetchAddNeed(paramsObj, submitFlag); //新增
        }
      } else if (operate == '提交') {
        /**needType 提交事件 固定为1*/
        params.needType = 1;

        /**校验【预估单价不能为空】*/
        if (!isExpectPrice) {
          message.error('请输入预估单价（元）!');
          return;
        }

        /**当状态=null,点击提交按钮为新增需求*/
        if (typeof needInfo?.state == 'undefined') {
          await fetchAddNeed(params, true);
        }

        /**当状态是需求编制时*/
        if (needInfo?.state == XQBZ_STATE()) {
          await fetchEditNeed(params, true);
        }

        /**状态为集中论证*/
        if (needInfo?.state == JZLZ_STATE()) {
          /**先掉用编辑接口，再打开流程弹窗*/
          const { msgFlag } = await editNeedRun(params);
          msgFlag && onChangeAuditRecordDrawerState(true);
        }
      } else if (operate == '计划下达') {
        fetchModifyNeedState(needInfo);
      } else if (operate == '保存') {
        tableForm?.validateFields()?.then((res) => {});
      }
    },
    cancelSubmit: async () => {
      return new Promise(async (resolve) => {
        const result = await cancelForm.validateFields();
        const params = {
          id: needInfo.id,
          versionNum: needInfo.versionNum,
          ...result,
        };
        resolve(await fetchCancelNeed(params));
      });
    },
    examineSubmit: async () => {
      return new Promise(async (resolve) => {
        const result = await examineForm.validateFields();
        const params = {
          // 审批记录的最后一个id
          id: needInfo.purchaseNeedChecks[needInfo.purchaseNeedChecks.length - 1]?.id ?? '',
          versionNum: needInfo.versionNum,
          ...result,
        };
        resolve(await fetchAuditNeed(params));
      });
    },
    exportSubmit: async () => {
      return new Promise(async (resolve) => {
        resolve(await fetchExportNeed());
      });
    },
  };

  /**
   * @saveMaterial 物料弹窗保存事件
   * @param info 选中的物料信息
   */
  const saveMaterial = (info: Record<string, any>[]) => {
    dispatch({
      type: IActionEnum.UPDATE_MATERIAL_LIST,
      payload: info ?? [],
    });
  };

  /**
   * 处理工作流功能 权限
   */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (needInfo?.state == `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1005`;
    const taskHandInfo: Record<string, any> = needInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [needInfo]);

  /**列表进入详情后获取详情信息 */
  useEffect(() => {
    if (!info) return;
    if (Object.keys(info).length) {
      fetchFindNeed({ id: info.id });
    }
  }, [info]);

  return {
    needInfo,
    needTitle,
    submit,
    loading,
    isView,
    form: {
      examineForm,
      cancelForm,
    },
    isShowState: {
      isShowMaterial,
      isShowCancel,
      isShowAuditRecord,
      isShowMaterialDetail,
      workflowPowerAllBtn,
      workFlowInfoObj,
      showSwitchFlow,
      isShowWorkflowCheck,
      nodesFlowListMemo,
    },
    change: {
      onChangeCancelModalState,
      onChangeMaterialModalState,
      onChangeAuditRecordDrawerState,
      onChangeMaterialDetailDrawerState,
      onChangeWorkFlowInfoObj,
      setShowSwitchFlow,
      closeSwitchFlowModal,
      fetchFindNeed,
      onChangeWorkflowCheck,
      reloadInfoFunc,
    },
    materialOperation: {
      saveMaterial,
      saveNeedAndMaterialParam,
    },
    tableForm,
  };
}
